# 创建 Timedelta （时间差）的方法以及与时间差相关的运算法则

import pandas as pd
import numpy as np

# 通过传递字符串可以创建 Timedelta 对象
print(pd.Timedelta('5 days 8 hours 6 minutes 59 seconds'))
# 5 days 08:06:59

print(pd.Timedelta(19, unit='h'))
# 0 days 19:00:00

print(pd.Timedelta(days=2, hours=6))
# 2 days 06:00:00

print(pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan']))
# TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015500', NaT], dtype='timedelta64[ns]', freq=None)

print(pd.to_timedelta(np.arange(5), unit='s'))
# TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02',
#                 '0 days 00:00:03', '0 days 00:00:04'],
#                dtype='timedelta64[ns]', freq=None)

s = pd.Series(pd.date_range('2020-1-1', periods=5, freq='D'))
#            A      B
# 0 2020-01-01 0 days
# 1 2020-01-02 1 days
# 2 2020-01-03 2 days
# 3 2020-01-04 3 days
# 4 2020-01-05 4 days

# 推导式用法
td = pd.Series([pd.Timedelta(days=i) for i in range(5)])
df = pd.DataFrame(dict(A=s, B=td))
print(df)
#            A      B          C
# 0 2020-01-01 0 days 2020-01-01
# 1 2020-01-02 1 days 2020-01-03
# 2 2020-01-03 2 days 2020-01-05
# 3 2020-01-04 3 days 2020-01-07
# 4 2020-01-05 4 days 2020-01-09

# 加法运算
df['C'] = df['A'] + df['B']
print(df)
# 减法运算
df['D'] = df['C'] - df['B']
print(df)
